<?php
namespace app\api\controller;

use app\api\validate\Entrust as ValidateEntrust;
use app\common\controller\Api;
use app\common\model\ShareEntrust;
use think\Cache;
use think\Db;

/**
 * 委托交易 
 * 方法列表：创建策略、补充、平仓
 */
class Entrust extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 控制器初始化工作
     * 限制：
     *   -在交易时间段内方能交易
     *   -用户实名认证后方能交易
     */
    public function _initialize()
    {
        parent::_initialize();

        $userInfo = $this->auth->getUser();
        
        // if( empty($userInfo->real_name) ){
        //     $this->error('请先设置实名信息再操作！');
        // }

        if( !isTradeTime() ){
            $this->error('当前时间不在交易时间段内');
        }
    }

     /**
     * 委托订单遍历
     * status 0 取消 1 委托中 2 成交
     */
    public function index()
    {
        $status = $this->request->param('status',1);
        $allNo = $this->request->param('all_no','');

        $userInfo = $this->auth->getUser();
        $where = [
            'user_id' => $userInfo->id,
            'status'  => $status
        ];
        if( $allNo ){
            $where['all_no'] = $allNo;
        }
        $entrustList = ShareEntrust::where($where)
                        ->order('id','desc')
                        ->select();
        if( $entrustList ){
            foreach($entrustList as &$value){
                $value['expire_time'] = date('Y-m-d H:i:s',bcadd($value['createtime'],1800));
                $value['create_time'] = date('Y-m-d H:i:s',$value['createtime']);
                $value['update_time'] = date('Y-m-d H:i:s',$value['updatetime']);
                $value['is_auto_text'] = $value->is_auto_text;
                $value['mode_text'] = $value->mode_text;
                $value['price'] = getActualTimeStockInfoByCode($value['all_no'],'price');
            }
        }
        if( $entrustList ){
            $this->success('查询成功',$entrustList);
        }else{
            $this->error('查询记录为空',[],0);
        }
    }

    /**
     * 历史委托
     */
    public function history()
    {
        $userInfo = $this->auth->getUser();
        $mode = $this->request->param('mode','');
        if( $mode && in_array($mode,['buy','sell']) == false ){
            $this->error('无效的交易模式mode');
        }
        $status = $this->request->param('status','');
        if( $status && in_array($status,['0','1','2']) == false ){
            $this->error('无效的交易状态status');
        }
        $where = [
            'user_id' => $userInfo->id
        ];
        if( $status ){
            $where['status'] = $status;
        }
        if( $mode ){
            $where['mode'] = $mode;
        }
        $entrustList = ShareEntrust::where($where)
                        ->order('id','desc')
                        ->select();
        foreach($entrustList as &$value){
            $value['create_time'] = date('Y-m-d H:i:s',$value['createtime']);
            $value['update_time'] = date('Y-m-d H:i:s',$value['updatetime']);
            $value['is_auto_text'] = $value->is_auto_text;
            $value['mode_text'] = $value->mode_text;
            $value['price'] = getActualTimeStockInfoByCode($value['all_no'],'price');
        }
        if( $entrustList ){
            $this->success('查询成功',$entrustList);
        }else{
            $this->error('查询记录为空',[],0);
        }
    }

    /**
     * 当日撤单
     */
    public function todayCanceOrder()
    {
        $userInfo = $this->auth->getUser();
        $start_time = strtotime(date('Y-m-d',time()));
        $end_time   = $start_time + 24*60*60;
        $where = [
            'user_id' => $userInfo->id,
            'status'  => '0',
            'updatetime' => [
                ['egt',$start_time],
                ['lt',$end_time]
            ]
        ];
        $entrustList = ShareEntrust::where($where)
                        ->order('id','desc')
                        ->select();
                       
        foreach($entrustList as &$value){
            $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
            $value['mode_text'] = $value->mode_text;
            $value['price'] = getActualTimeStockInfoByCode($value['all_no'],'price');
        }
        if( $entrustList ){
            $this->success('查询成功',$entrustList);
        }else{
            $this->error('查询记录为空',[]);
        }
    }

    /**
     * 创建委托
     */
    public function create()
    {
        $params = $this->request->post();
        $validate = new ValidateEntrust();
        if(!$validate->scene('create')->check($params)){
            return $this->error($validate->getError());
        }
        
        $userInfo = $this->auth->getUser();
        $where = [
            'user_id' => $userInfo->id,
            'all_no'  => $params['all_no'],
            'status'  => 1 
        ];
        // $strategyInfo = ShareEntrust::where($where)->find();
        // if( $strategyInfo ){
        //     $this->error('已存在委托');
        // }

        //保证金
        $earnestMoney = $params['deal_price'] * $params['num'] / 10;
        
        Db::startTrans();
        try {
            $stockname = getActualTimeStockInfoByCode($params['all_no'],'name');
             //组装数据
             $params['user_id']          = $userInfo->id;
             $params['name']             = $stockname;
             $params['is_auto']          = $params['isAuto'];
             $params['total_earnest']    = $earnestMoney;

             //创建新策略
            $entrustModel = new ShareEntrust();
            $entrustModel->allowField(true)->save($params);

            //扣除余额
            updateMoney($userInfo,-$earnestMoney,'委托保证金');

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('生成策略失败：'.$e->getMessage());
        }
        // 创建等待成交集合
        $redis = Cache::store('redis')->handler();
        $entInfo = sprintf('%s-%s-%s-%s',
            $entrustModel->all_no,
            $entrustModel->deal_price,
            $entrustModel->createtime,
            $entrustModel->id
        );
        $res = $redis->lpush('entrust:list:waitdeal',$entInfo);
        $this->success('委托成功');
    }

    /**
     * 手动撤销委托
     * @method get
     * @param  id  委托单id
     */
    public function revoke()
    {
        $id = $this->request->get('id');
        $userInfo = $this->auth->getUser();

        $where = [
            'user_id' => $userInfo->id,
            'id'      => $id,
            'status'  => 1 
        ];
        $strategyEntrust = ShareEntrust::where( $where)->find();
        if( !$strategyEntrust ){
            $this->error('没有找到对应委托');
        }
        
        if($strategyEntrust->revoke()){
            $this->success('委托撤销成功');
        }else{
            $this->error('委托撤销失败');
        }
    }

    /**
     * 委托成交
     */
    public function deal()
    {
        $params = $this->request->post();
        $validate = new ValidateEntrust();
        if(!$validate->scene('create')->check($params)){
            return $this->error($validate->getError());
        }
        
        $userInfo = $this->auth->getUser();
        $stockname = getActualTimeStockInfoByCode($params['all_no'],'name');

        //保证金
        $earnestMoney = $params['deal_price'] * $params['num'] / 10;

        Db::startTrans();
        try {
             //组装数据
             $params['user_id']          = $userInfo->id;
             $params['name']             = $stockname;
             $params['is_auto']          = $params['isAuto'];
             $params['total_earnest']    = $earnestMoney;

             //创建新策略
            $entrustModel = new ShareEntrust();
            $entrustModel->allowField(true)->save($params);

            //扣除余额
            updateMoney($userInfo,-$earnestMoney,'委托保证金');

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('生成策略失败：'.$e->getMessage());
        }
        // 创建等待成交集合
        $redis = Cache::store('redis')->handler();
        $redis->sadd('entrust:set:waitdeal',"{$entrustModel->all_no}-{$entrustModel->deal_price}");
        $this->success('委托成功');
    }

   
}    
